/* eslint-disable camelcase */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Breadcrumb, Button, Popover, Tabs } from 'antd';
import { Link } from 'react-router-dom';
import _ from 'lodash';
import { withRouter } from 'react-router';
import { getOnedayDetail } from '@api/task';
import { LEVEL_TEXT } from '@util/constants';
import OnedayModal from '../list/components/oneday-detection-modal';
import fatalThreatenImg from './image/fatalThreaten.svg';
import highThreatenImg from './image/highThreaten.svg';
import middleThreatenImg from './image/middleThreaten.svg';
import lowThreatenImg from './image/lowThreaten.svg';
import SiteList from './components/site-list';
import ExportModal from '@components/export-modal';
import { exportAssetForm, getAssetFormList, downloadAssetForm, deleteAssetForm } from '@api/asset';
import './index.less';

const prefixCls = 'oneday-detection-detail';

export const LEVEL_THREATEN_IMG = {
  fatal: fatalThreatenImg,
  high: highThreatenImg,
  middle: middleThreatenImg,
  low: lowThreatenImg
};

class OneDayDetectionDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeTabKey: '',
      oneDayModalVisible: false,
      attrModalVisible: false,
      detail: {},
      exportConfig: {},
      exportModalVisible: false,
      cache: _.get(this.props, 'location.state.cache', '')
    };
    this.onedayId = _.get(this.props, 'match.params.id');
  }

  componentDidMount() {
    window.onpopstate = () => {
      if (this.state.cache) {
        const params = new URLSearchParams(window.location.search);
        params.set('query', this.state.cache);
        // 将新的参数添加到浏览器历史记录
        window.history.replaceState({}, '', `${window.location.pathname}?${params.toString()}`);
      }
    };
    this.getOnedayDetail();
  }

  exportAssetForm = config => {
    this.setState({
      exportConfig: config,
      exportModalVisible: true
    });
  };

  getOnedayDetail = () => {
    getOnedayDetail(this.onedayId).then(res => {
      this.setState({ detail: _.get(res.data, 'data.detail', {}) });
    });
  };

  changeModalVisible = visible => {
    this.setState({
      oneDayModalVisible: visible
    });
  };

  //单个漏洞的下发检测
  onSingleSubmit = () => {
    this.setState({ oneDayModalVisible: false });
  };

  render() {
    const { oneDayModalVisible, detail, exportModalVisible } = this.state;
    const onedayId = _.get(detail, '_id');
    const hasPoc = Boolean(_.get(detail, 'poc.length'));
    const level = _.get(detail, 'level', 'low');
    const owasp = _.get(detail, 'owasp', []);
    const affectedVersion = _.get(detail, 'affected_version', []);
    const related = _.get(detail, 'related', []);
    const vulCategory = _.get(detail, 'vul_category', '-');
    const affected = _.get(detail, 'affected', '-');
    const cveId = _.get(detail, 'cve_id', '-');
    const cnnvdId = _.get(detail, 'cnnvd_id', '-');
    const cnvdId = _.get(detail, 'cnvd_id', '-');
    const cwe = _.get(detail, 'cwe', '-');
    const cvss3 = _.get(detail, 'cvss_3', '-');

    const exportModalConfig = {
      visible: exportModalVisible,
      target: '资产报表',
      enableRangePick: false,
      onVisibleChange: exportModalVisible => this.setState({ exportModalVisible }),
      listLoader: getAssetFormList,
      downloadDispatcher: () => exportAssetForm(this.state.exportConfig),
      downloader: downloadAssetForm,
      deleter: deleteAssetForm
    };

    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-bread`}>
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to={{ pathname: '/vul/oneday-detection', state: { cache: this.state.cache } }}>
                {' '}
                1day 漏洞插件列表
              </Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>
              <span style={{ fontWeight: 600 }}>详情</span>
            </Breadcrumb.Item>
          </Breadcrumb>
        </div>
        <div className={`${prefixCls}-header`}>
          <div className={`${prefixCls}-header-left`}>
            <img src={LEVEL_THREATEN_IMG[level]} />
            <div className={`${prefixCls}-header-left-level`}>{LEVEL_TEXT[level]}</div>
            {hasPoc ? (
              <Button type="primary" onClick={() => this.changeModalVisible(true)}>
                下发检测
              </Button>
            ) : null}
          </div>
          <div className={`${prefixCls}-header-right`}>
            <div>
              <span style={{ color: '#1E1F23' }}>{_.get(detail, 'name', '-')}</span>
              <span className={`${prefixCls}-header-right-type`}>
                {_.get(detail, 'vul_type', '-')}
              </span>
            </div>
            <div className={`${prefixCls}-header-right-bottom`}>
              <div className={`${prefixCls}-header-right-bottom-name`}>
                <span>漏洞分类</span>
                <br />
                <span>影响组件</span>
                <br />
                <span>披露时间</span>
              </div>
              <div className={`${prefixCls}-header-right-bottom-value`}>
                {vulCategory.length > 25 ? (
                  <Popover placement="topLeft" content={vulCategory}>
                    <span>{vulCategory}</span>
                  </Popover>
                ) : (
                  <span>{vulCategory || '-'}</span>
                )}
                <br />
                {affected.length > 25 ? (
                  <Popover placement="topLeft" content={affected}>
                    <span>{affected}</span>
                  </Popover>
                ) : (
                  <span>{affected || '-'}</span>
                )}
                <br />
                <span>{_.get(detail, 'lanched', '-')}</span>
              </div>
              <div className={`${prefixCls}-header-right-bottom-name`}>
                <span>CVE ID</span>
                <br />
                <span>CNNVD ID</span>
                <br />
                <span>CNVD ID</span>
              </div>
              <div className={`${prefixCls}-header-right-bottom-value`}>
                {cveId.length > 25 ? (
                  <Popover placement="topLeft" content={cveId}>
                    <span>{cveId}</span>
                  </Popover>
                ) : (
                  <span>{cveId || '-'}</span>
                )}
                <br />
                {cnnvdId.length > 25 ? (
                  <Popover placement="topLeft" content={cnnvdId}>
                    <span>{cnnvdId}</span>
                  </Popover>
                ) : (
                  <span>{cnnvdId || '-'}</span>
                )}
                <br />
                {cnvdId.length > 25 ? (
                  <Popover placement="topLeft" content={cnvdId}>
                    <span>{cnvdId}</span>
                  </Popover>
                ) : (
                  <span>{cnvdId || '-'}</span>
                )}
              </div>
              <div className={`${prefixCls}-header-right-bottom-name`}>
                <span>CWE</span>
                <br />
                <span>OWASP</span>
                <br />
                <span>CVSS 3.0</span>
              </div>
              <div className={`${prefixCls}-header-right-bottom-value`}>
                {cwe.length > 25 ? (
                  <Popover placement="topLeft" content={cwe}>
                    <span>{cwe}</span>
                  </Popover>
                ) : (
                  <span>{cwe || '-'}</span>
                )}
                <br />
                <span>
                  {owasp.length === 0 ? '-' : ''}
                  {owasp.map((item, index) => {
                    return index !== owasp.length - 1 ? (
                      <Popover key={index} placement="topLeft" content={`${item},`}>
                        <span key={index}>{item},&nbsp;</span>
                      </Popover>
                    ) : (
                      <span>{item}</span>
                    );
                  })}
                </span>
                <br />
                {cwe.length > 25 ? (
                  <Popover placement="topLeft" content={cvss3}>
                    <span>{cvss3}</span>
                  </Popover>
                ) : (
                  <span>{cvss3 || '-'}</span>
                )}
              </div>
            </div>
          </div>
        </div>

        <div className={`${prefixCls}-body`}>
          <Tabs onChange={activeTabKey => this.setState({ activeTabKey })}>
            <Tabs.TabPane tab="漏洞详情" key="vul-detail">
              <div className={`${prefixCls}-body-item`}>
                <div className={`${prefixCls}-body-item-title`}>漏洞描述</div>
                <p>{_.get(detail, 'description', '').trim() || '暂无'}</p>
              </div>

              <div className={`${prefixCls}-body-item`}>
                <div className={`${prefixCls}-body-item-title`}>影响范围</div>
                <div className={`${prefixCls}-body-item-affected-box`}>
                  {affectedVersion.length === 0 ? '暂无' : ''}
                  {affectedVersion.map(item => {
                    return (
                      <span key={item} className={`${prefixCls}-body-item-affected`}>
                        {item}
                      </span>
                    );
                  })}
                </div>
              </div>

              <div className={`${prefixCls}-body-item`}>
                <div className={`${prefixCls}-body-item-title`}>漏洞危害</div>
                <p>{_.get(detail, 'harm', '').trim() || '暂无'}</p>
              </div>

              <div className={`${prefixCls}-body-item`}>
                <div className={`${prefixCls}-body-item-title`}>修复建议</div>
                <p>{_.get(detail, 'suggestion', '').trim() || '暂无'}</p>
              </div>

              <div className={`${prefixCls}-body-item`}>
                <div className={`${prefixCls}-body-item-title`}>相关链接</div>
                {related.length === 0 ? '暂无' : ''}
                {related.map(item => {
                  return <p key={item}>{item}</p>;
                })}
              </div>
            </Tabs.TabPane>
            <Tabs.TabPane
              tab={`真实影响资产(${_.get(detail, 'affectedSiteCount.real', 0)})`}
              key="real"
            >
              <SiteList
                desc="真实影响资产"
                type="real"
                active={this.state.activeTabKey === 'real'}
                onedayId={onedayId}
                exportAssetForm={this.exportAssetForm}
                reloadOneday={this.getOnedayDetail}
                baseQuery={{ oneday: [onedayId] }}
              />
            </Tabs.TabPane>
            <Tabs.TabPane
              tab={`可能影响资产(${_.get(detail, 'affectedSiteCount.suspect', 0)})`}
              key="may"
            >
              <SiteList
                desc="可能影响资产"
                type="suspect"
                active={this.state.activeTabKey === 'suspect'}
                onedayId={onedayId}
                exportAssetForm={this.exportAssetForm}
                reloadOneday={this.getOnedayDetail}
                baseQuery={{ suspectedOneday: [onedayId] }}
              />
            </Tabs.TabPane>
            <Tabs.TabPane
              tab={`已忽略资产(${_.get(detail, 'affectedSiteCount.ignore', 0)})`}
              key="ignore"
            >
              <SiteList
                desc="已忽略资产"
                type="ignore"
                active={this.state.activeTabKey === 'ignore'}
                onedayId={onedayId}
                exportAssetForm={this.exportAssetForm}
                reloadOneday={this.getOnedayDetail}
                baseQuery={{ ignoredOneday: [onedayId] }}
              />
            </Tabs.TabPane>
          </Tabs>
        </div>
        <OnedayModal
          modalVisible={oneDayModalVisible}
          changeModalVisible={this.changeModalVisible}
          onClickSubmit={this.onSingleSubmit}
          onedays={[detail]}
        />
        <ExportModal {...exportModalConfig} />
      </div>
    );
  }
}

OneDayDetectionDetail.propTypes = {
  history: PropTypes.object,
  match: PropTypes.object
};

export default withRouter(OneDayDetectionDetail);
